<template>
  <div class="lyric">
    <div class="song-info">
      <span class="name">{{ info.name }}</span>
      <ul class="detail">
        <li>
          专辑: <span class="album cm ofh">{{ info.album }}</span>
        </li>
        <li>
          歌手: <span class="singer cm ofh">{{ info.singer }}</span>
        </li>
        <li>
          来源: <span class="source cm ofh">{{ info.album }}</span>
        </li>
      </ul>
    </div>
    <div class="wrapper">
      <div class="lrc" ref="lrc">
        <ul id="ullrc"  :style="{ marginTop: top / 10 + 'rem' }">
          <li
            class="ofh"
            v-for="(item, i) in lrcs"
            :key="item.time"
            :class="{ active: activeIndex === i }"
          >
            {{ item.words }}
          </li>
        </ul>
      </div>
    </div>
    <audio ref="audio" :src="url" style="display: none"></audio>
  </div>
</template>

<script>
import axios from "@/utils/axios";
export default {
  name: "Lyric",
  data() {
    return {
      url: "",
      activeIndex: "",
      top: 0,
      lrcs: [],
      info: {},
      audio: this.$store.state.audio,
    };
  },
  methods: {
    changeScrollTop() {
      const lrc = this.$refs.lrc;
      lrc.scrollTop += 100;
    },
    /**
     * 将歌词字符串转换为数组返回
     * [{time:1.06, words:"难念的经"}, {time:3.95, words:"演唱：周华健"}]
     */
    getLrcArray(lrc) {
      //1. ["[00:01.06]难念的经", "[00:03.95]演唱：周华健", ....]
      let parts = lrc.split("\n");
      //2. [{time:1.06, words:"难念的经"}, {time:3.95, words:"演唱：周华健"}]
      for (let i = 0; i < parts.length; i++) {
        parts[i] = getLrcObj(parts[i]);
      }
      return parts;

      // "[00:01.06]难念的经"  --->  {time:1.06, words:"难念的经"}
      function getLrcObj(content) {
        let twoParts = content.split("]");
        // 取出时间
        let time = twoParts[0].substr(1);
        let timeParts = time.split(":");
        let minute = +timeParts[0]; //分钟
        let seconds = +timeParts[1]; //秒
        time = minute * 60 + seconds;
        // 取出文字
        let words = twoParts[1];

        return {
          time: time,
          words: words,
        };
      }
    },
    /**
     * 根据当前播放的时间，匹配到对应的歌词，得到该歌词的下标
     */
    getLrcIndex() {
      let time = this.audio.currentTime; //当前播放的时间
      for (let i = 0; i < this.lrcs.length; i++) {
        if (time < this.lrcs[i].time) {
          return i - 1;
        }
      }
    },
    /**
     * 只要一调用这个函数，就把歌词滚动到最合适的位置
     */
    setPositioin(isStop) {
      let i = this.getLrcIndex();
      if (i === -1) {
        return; //最开始的情况，没有命中任何一句歌词，不管它
      }
      // 假设当前播放的是第 i 句歌词
      let top = i * 35 + 35 / 2 - 320 / 2;
      if (top < 0) {
        top = 0; // top最小为0
      }
      //   this.top = -top ;
      if (isStop !== true) {
        this.$refs.lrc && (this.$refs.lrc.scrollTop = top);
      }
      // 高亮显示当前歌词
      this.activeIndex = i;
    },
    getLyric(id) {
      if (id) {
        axios.get("/lyric", { params: { id } }).then((res) => {
          const r = this.getLrcArray(res.lrc.lyric);
          this.lrcs = r;
        });
        axios.get("/song/url", { params: { id } }).then((res) => {
          this.url = res.data[0].url;
        });
        axios.get("/song/detail", { params: { ids: id } }).then((res) => {
          const data = res.songs[0];
          const obj = {};
          obj.name = data.name;
          obj.singer = data.ar[0].name;
          obj.album = data.al.name;
          this.$bus.$emit("sendImgUrl", { url: data.al.picUrl, id: id });
          this.info = obj;
        });
      }
    },
  },
  created() {
    // 赋给歌词
    const id = this.$route.params.id || 33894312;
    if (id) {
      this.getLyric(id);
      this.audio && (this.audio.ontimeupdate = this.setPositioin);
      // 图片旋转起来
      this.$bus.$emit("changeStutas");
    }
    this.$bus.$on("getSong", ({ id, audio }) => {
      // 得到id和播放器
      this.getLyric(id);
      this.audio = audio;
      this.audio && (this.audio.ontimeupdate = this.setPositioin);
    });
  },
  mounted() {
    // let audio = (this.audio = this.$refs.audio);
    // 监听音乐变化

    this.$refs.lrc.onscroll = () => {
      this.audio.ontimeupdate = null;
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.setPositioin(true);
      //   如果一段时间没有滚动，那么重新监听
      this.timer = setTimeout(() => {
        this.audio.ontimeupdate = this.setPositioin;
      }, 2000);
    };
    let id = localStorage.getItem("id");
    if (id) {
      this.getLyric(id);
    }
  },
  beforeDestroy() {
    clearTimeout(this.timer);
  },
};
</script>

<style lang="scss" scoped>
.lyric {
  width: 55rem;
  padding: 3rem;
  .song-info {
    .name {
      font-size: 2.7rem;
      font-weight: bold;
    }
    .detail {
      display: flex;
      margin-top: 1rem;
      justify-content: space-between;
      li {
        display: flex;
        align-items: center;
        .cm {
          display: inline-block;
          color: lightblue;
          width: 11rem;
        }
      }
    }
  }

  .wrapper {
    height: 32rem;
  }
  .lrc {
    height: 100%;
    margin-top: 30px;
    color: #888;
    overflow: auto;
    ul {
      margin: 0;
      padding: 0;
      list-style: none;
      text-align: center;
      /* 表示ul的样式变化，在0.3秒内完成，而不是瞬间完成 */
      transition: 0.3s;
      li {
        height: 35px;
        line-height: 35px;
        transition: 0.3s;
      }
      /* 高亮的歌词效果 */
      li.active {
        color: #000;
        font-size: 1.2em;
        font-weight: bold;
      }
    }
  }
  .lrc::-webkit-scrollbar {
    width: 5px;
    height: 1px;
  }

  .lrc::-webkit-scrollbar-thumb {
    border-radius: 5px;
    background: #e0e0e0;
  }

  .lrc::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    border-radius: 5px;
  }
}
</style>